package com.bsb.biz.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bsb.base.common.config.Const;
import com.bsb.base.common.util.StringUtils;
import com.bsb.base.model.SysOrganization;
import com.bsb.base.model.SysUser;
import com.bsb.base.model.SysUserExample;
import com.bsb.base.model.SysUserExample.Criteria;
import com.bsb.base.model.UpdatePwd;
import com.bsb.biz.service.PasswordHelper;
import com.bsb.biz.service.SysOrganizationService;
import com.bsb.biz.service.SysRoleService;
import com.bsb.biz.service.SysUserRoleService;
import com.bsb.biz.service.SysUserService;
import com.bsb.biz.shiro.UserUtils;

@Controller
@RequestMapping("/user")
public class SysUserController {

	private int defaultPageSize = 10;

	private String redirect = "redirect:/user";

	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysOrganizationService sysOrganizationService;
	@Resource
	private SysRoleService sysRoleService;
	@Resource
	private PasswordHelper passwordHelper;
	@Resource
	private SysUserRoleService sysUserRoleService;

	@RequiresPermissions("user:view")
	@RequestMapping(method = RequestMethod.GET)
	public String list(Model model, @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@RequestParam(value = "pageSize", required = false) Integer pageSize) {
		int maxPageNum = 0;
		if (pageSize == null) {
			pageSize = defaultPageSize;
		}
		SysUserExample sysUserExample = new SysUserExample();
		Criteria criteria = sysUserExample.createCriteria();
		SysUser currentUser = UserUtils.currentUser();
		Long id = currentUser.getId();
		if(id!=Const.SUPER_ADMIN){
			criteria.andOrganization_idIn(sysUserService.getDeptIdsByUser());
			criteria.andIdNotEqualTo(id);
			criteria.andIdNotEqualTo(1l);
		}
		int totalCount = sysUserService.countSysUser(sysUserExample);
		if (totalCount % pageSize == 0) {
			maxPageNum = totalCount / pageSize;
		} else {
			maxPageNum = totalCount / pageSize + 1;
		}
		if (pageNum == null || pageNum < 1) {
			pageNum = 1;
		} else {
			if (maxPageNum > 0 && pageNum > maxPageNum) {
				pageNum = maxPageNum;
			}
		}
		sysUserExample.setPageIndex((pageNum - 1) * pageSize);
		sysUserExample.setPageSize(pageSize);
		List<SysUser> sysUsers = sysUserService.getPageSysUser(sysUserExample);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		if (totalCount % pageSize == 0) {
			model.addAttribute("maxPageNum", totalCount / pageSize);
		} else {
			model.addAttribute("maxPageNum", totalCount / pageSize + 1);
		}
		model.addAttribute("userList", sysUsers);
		return "/SysUser/list";
	}

	@RequiresPermissions("user:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String toAdd(Model model) {
		setCommonData(model);
		model.addAttribute("user", new SysUser());
		model.addAttribute("op", "新增");
		return "/SysUser/edit";
	}

	@RequiresPermissions("user:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String add(Model model, RedirectAttributes redirectAttributes, @ModelAttribute("user") SysUser sysUser) {
		String username = sysUser.getUsername();
		SysUser userByUsername = sysUserService.getUserByUsername(username);
		if (null != userByUsername) {
			redirectAttributes.addFlashAttribute("msg", "用户名" + username + "已存在");
			return "redirect:/user/create";
		}
		passwordHelper.encryptPassword(sysUser);
		sysUserService.addUser(sysUser);
		redirectAttributes.addFlashAttribute("msg", "新增成功");
		return redirect;
	}

	@RequiresPermissions("user:delete")
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	public String del(@PathVariable("id") Long id, Model model) {
		setCommonData(model);
		model.addAttribute("user", sysUserService.getSysUserById(id));
		model.addAttribute("op", "删除");
		return "SysUser/edit";
	}

	@RequiresPermissions("user:delete")
	@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		sysUserService.delSysUser(id);
		redirectAttributes.addFlashAttribute("msg", "删除成功");
		return redirect;
	}

	@RequiresPermissions("user:update")
	@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	public String toEdit(Model model, @PathVariable("id") Long id) {
		setCommonData(model);
		SysUser sysUserById = sysUserService.getSysUserById(id);
		List<Long> queryRoleIdList = sysUserRoleService.queryRoleIdList(id);
		sysUserById.setRole_ids(StringUtils.join(queryRoleIdList.toArray(), ","));
		model.addAttribute("roleList", sysRoleService.getRolesByDeptid(sysUserById.getOrganization_id()));
		model.addAttribute("user", sysUserById);
		model.addAttribute("op", "修改");
		return "/SysUser/edit";
	}

	@RequiresPermissions("user:update")
	@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
	public String edit(Model model,@PathVariable("id") Long id,
			RedirectAttributes redirectAttributes, @ModelAttribute("user") SysUser sysUser) {
		String role_ids = sysUser.getRole_ids();
		if(StringUtils.isEmpty(role_ids)){
			redirectAttributes.addFlashAttribute("msg", "角色不能为空");
			return "redirect:/user/"+id+"/update";
		}
		sysUserService.updateUser(sysUser);
		redirectAttributes.addFlashAttribute("msg", "修改成功");
		return redirect;
	}

	@RequiresPermissions("user:update")
	@RequestMapping(value = "/{id}/changePassword", method = RequestMethod.GET)
	public String showChangePasswordForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute("user", sysUserService.getSysUserById(id));
		model.addAttribute("op", "修改密码");
		return "SysUser/changePassword";
	}

	@RequiresPermissions("user:update")
	@RequestMapping(value = "/{id}/changePassword", method = RequestMethod.POST)
	public String changePassword(@PathVariable("id") Long id, String newPassword,
			RedirectAttributes redirectAttributes) {
		sysUserService.changePassword(id, newPassword);
		redirectAttributes.addFlashAttribute("msg", "修改密码成功");
		return "redirect:/user";
	}

	@RequestMapping("/sysUser/view")
	public String view(Model model, @RequestParam(value = "id", required = true) Long id) {
		SysUser sysUser = sysUserService.getSysUserById(id);
		model.addAttribute("sysUser", sysUser);
		return "/SysUser/view";
	}

	private void setCommonData(Model model) {
		//数据权限
        List<SysOrganization> subDeptList = sysOrganizationService.getSubDeptList();
		model.addAttribute("dataDeptList", subDeptList);
		//添加时默认不显示角色，部门和角色联动。修改时角色要回显   分开单独处理
//		model.addAttribute("roleList", sysRoleService.getRolesByDeptid(UserUtils.currentUser().getOrganization_id()));
	}
	
	@RequestMapping("/checkOldpwd")
	@ResponseBody
	public Object checkOldpwd(@RequestParam(value = "oldpwd", required = true) String oldpwd) {
		SysUser currentUser = UserUtils.currentUser();
		String credentialsSalt = currentUser.getCredentialsSalt();
		String password = currentUser.getPassword();
		String encryptPassword = passwordHelper.encryptPassword(oldpwd, credentialsSalt);
		if(password.equals(encryptPassword)){
			return true;
		}
		return false;
	}
	
	@RequestMapping(value = "/updatePwd", method = RequestMethod.GET)
	public String toUpdatePwd(){
		return "/SysUser/updatePwd";
	}
	
	@RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
	public String updatePwd(@ModelAttribute("updatePwd") UpdatePwd updatePwd,
			RedirectAttributes redirectAttributes) {
		String oldpwd = updatePwd.getOldpwd();
		SysUser currentUser = UserUtils.currentUser();
		String credentialsSalt = currentUser.getCredentialsSalt();
		String password = currentUser.getPassword();
		String encryptPassword = passwordHelper.encryptPassword(oldpwd, credentialsSalt);
		if(!password.equals(encryptPassword)){
			redirectAttributes.addFlashAttribute("msg", "原密码不正确");
			return "/SysUser/updatePwd";
		}
		Long id = currentUser.getId();
		String newpwd = updatePwd.getNewpwd();
		sysUserService.changePassword(id, newpwd);
		SecurityUtils.getSubject().logout();
		redirectAttributes.addFlashAttribute("msg", "修改密码成功请重新登录");
		return "login";
	}
}
